package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;


    @Value("${minio.endpointUrl}")
    private String endpointUrl;
    /**
     * 文件上传管理
     *
     * @param file
     * @return
     */
    @Override
    public String saveFile(MultipartFile file) {
        String fileName= null;
        try {
            //创建存储空间 访问权限为Public gmall
            boolean found=    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            //判断是否有
            if (!found){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
            }
            //1.构建上传文件 文件对象的标识 UUid +时间戳 /a/a.png
            //1.1获取文件的后缀
            String extName=  StringUtils.substringAfter(file.getOriginalFilename(),".");
            //1.2 封装文件名称
            fileName = DateUtil.formatDate(new Date())+"/"+
                    UUID.randomUUID().toString().replace("-", "")+"."+extName;
            //2.调用MInioclient对象方法创建完成文件上传
            //2.调用Minioclient对象方法完成文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            //3.拼接上传后文件地址即可
            return endpointUrl + "/" + bucketName + "/" + fileName;

        }  catch (Exception e) {
            throw new RuntimeException(e);
        }




    }
}
